package com.shoplook2025.good.api.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shoplook2025.core.utils.utils.JsonResult;
import com.shoplook2025.good.model.Goods;
import com.shoplook2025.good.model.search.GoodsSearchBean;
import com.shoplook2025.good.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yan
 * @date 2025/8/26
 */
@RestController
@RequestMapping(value = "/api/goods",produces = MediaType.APPLICATION_JSON_VALUE)
public class GoodsApi {

    private GoodsService goodsService;
    @Autowired
    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(@RequestParam(defaultValue = "10") Integer pageSize,
                                                 @RequestParam(defaultValue = "1") Integer pageNo,
                                                 GoodsSearchBean gsb){
        Page<Goods> page = Page.of(pageNo,pageSize);
        page = this.goodsService.findAll(page,gsb);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>> findById(@PathVariable Integer id){
        Goods goods = this.goodsService.findById(id);
        if(goods==null){
            return ResponseEntity.ok(JsonResult.fail("未找到该商品"));
        }else {
            return ResponseEntity.ok(JsonResult.success(goods));
        }
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody Goods goods){
        int count = this.goodsService.save(goods);
        if(count > 0){
            return ResponseEntity.ok(JsonResult.success(count));
        }else {
            return ResponseEntity.ok(JsonResult.fail("保存失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Goods goods){
        boolean flag = this.goodsService.update(goods);
        if(flag){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(Integer[] ids){
        int count = this.goodsService.deleteByIds(List.of(ids));
        if(count > 0){
            return ResponseEntity.ok(JsonResult.success(count));
        }else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }
}
